﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; 

namespace Algobox.JuicyLib.Services
{
    public abstract class ServiceManager
    {
        /// <summary>
        /// worker thread
        /// </summary>
        protected Thread workerThread = null;
        /// <summary>
        /// thread name
        /// </summary>
        protected string threadName;


        /// <summary>
        /// provides insight to the state of the worker thread
        /// </summary>
        public ThreadState ThreadStatus
        {
            get
            {
                if (workerThread == null)
                    return ThreadState.Unstarted;
                else
                    return workerThread.ThreadState;
            }
        }


        public ServiceManager()
        { 
            
        }

        public ServiceManager(string threadNameIn)
        {
            threadName = threadNameIn;
        }

        protected void Initialize()
        { 
            
        }

        /// <summary>
        /// set wait in milliseconds 
        /// </summary>
        protected int sleepInterval = 1;

        /// <summary>
        /// variable used to control thread loop
        /// </summary>
        protected bool continueProcessing = true;

        /// <summary>
        /// start process thread
        /// </summary>
        /// <returns></returns>
        public virtual bool Start()
        {
            bool ret = true;

            continueProcessing = true;

            Process();

            return ret;
        }

        /// <summary>
        /// stop processing thread
        /// </summary>
        public virtual void Stop()
        {
            if (workerThread != null)
            {
                //kill 
                workerThread.Abort();
                //wait for death
                workerThread.Join(); 
                workerThread = null;
            }
        }

        public virtual void Process()
        {
            //please override
        }
    }
}
